package com.sdweizan.sdk.bytedance.api.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.sdweizan.sdk.bytedance.api.BdOpenService;
import com.sdweizan.sdk.bytedance.bean.BdBaseResponse;
import com.sdweizan.sdk.bytedance.bean.payment.general.*;
import com.sdweizan.sdk.bytedance.bean.refund.general.*;
import com.sdweizan.sdk.bytedance.config.BdConfigStorage;
import com.sdweizan.sdk.bytedance.error.BdErrorException;
import com.sdweizan.sdk.bytedance.util.SignUtils;
import lombok.AllArgsConstructor;

/** 抖音-通用交易服务 * */
@AllArgsConstructor
public class BdGeneralTransactionService {
  private final BdOpenService bdOpenService;

  public BdGeneralQueryOrderResponse queryOrder(BdGeneralQueryOrderRequest queryOrderRequest)
      throws BdErrorException {
    return bdOpenService.post(
        queryOrderRequest, new TypeReference<BdGeneralQueryOrderResponse>() {});
  }

  /** * *更新履约状态 * * */
  public BdGeneralFulfillStatusResponse updateFulfillStatus(
      BdGeneralFulfillStatusRequest fulfillStatusRequest) throws BdErrorException {
    return bdOpenService.post(
        fulfillStatusRequest, new TypeReference<BdGeneralFulfillStatusResponse>() {});
  }

  /** 发起退款* */
  public BdGeneralCreateRefundResponse generalCreateRefund(
      BdGeneralCreateRefundRequest refundRequest) throws BdErrorException {
    return bdOpenService.post(refundRequest, new TypeReference<BdGeneralCreateRefundResponse>() {});
  }

  /** 同步退款审核结果* */
  public BdBaseResponse generalSyncRefundResult(
      BdGeneralSyncRefundResultRequest refundResultRequest) throws BdErrorException {
    return bdOpenService.post(refundResultRequest, new TypeReference<BdBaseResponse>() {});
  }

  /** 查询退款* */
  public BdGeneralQueryRefundResponse generalQueryRefund(
      BdGeneralQueryRefundRequest queryRefundRequest) throws BdErrorException {
    return bdOpenService.post(
        queryRefundRequest, new TypeReference<BdGeneralQueryRefundResponse>() {});
  }

  /**
   * 提供预下单能力，开发者通过调用该方法生成订单，返回订单号和订单信息。
   *
   * <p>https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/api/industry/general_trade/create_order/requestOrder
   *
   * @param orderDataRequest
   * @return
   */
  public BdGeneralOrderDataResponse generateOrderSignAndData(
      BdGeneralOrderDataRequest orderDataRequest) {
    BdConfigStorage configStorage = bdOpenService.getBdMiniAppService().getConfigStorage();
    String data = JSON.toJSONString(orderDataRequest);
    return BdGeneralOrderDataResponse.builder()
        .sign(
            SignUtils.getByteAuthorization(
                "POST",
                "/requestOrder",
                data,
                configStorage.getAppId(),
                configStorage.getAppPrivateKey()))
        .data(data)
        .build();
  }
}
